/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package srm;

import java.util.*;
import java.util.regex.*;
import java.text.*;
import java.math.*;

public class CountingSeries {

    public long countThem(long a, long b, long c, long d, long upperBound) {
        HashSet<Long> s = new HashSet<Long>();

        long f;
        long count1 = 0;

        if (upperBound >= a) {
            count1 = (upperBound - a) / b + 1;
        }

        for (long y = 0;; y++) {
            f = c * (long) Math.pow((double) d, (double) y);

            if (d == 1) {
                if (f - a < 0 && f <= upperBound)
                    s.add(f);
                else if ((f - a) >= 0 && (f - a) % b != 0 && f <= upperBound)
                    s.add(f);
                
                break;
            }
            else {
                if (f <= upperBound && (f - a) >= 0 && (f - a) % b == 0) {
                    continue;
                }

                if (f <= upperBound) {
                    s.add(f);
                }
                else {
                    break;
                }
            }
        }

        return count1 + s.size();
    }

    public static void main(String[] args) {
        CountingSeries cs = new CountingSeries();
        System.out.println(cs.countThem(17340, 40451, 7763, 1, 3462));
    }
}
//Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
